import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

// 路由懒加载方式
const Tabbar = () => import('@/components/app-tabbar.vue')
const Home = () => import('@/views/home')
const User = () => import('@/views/user')
const Add = () => import('@/views/add')
const List = () => import('@/views/list')
const Login = () => import('@/views/login')
const errorPage = () => import('@/views/error/404')

const routes = [
  // 路由规则
  {
    path: '/',
    components: { default: Home, tabbar: Tabbar },
    meta: { title: '首页', auto: false }
  },
  {
    path: '/user',
    components: { default: User, tabbar: Tabbar },
    meta: { title: '用户中心', auto: true }
  },
  {
    path: '/list',
    components: { default: List, tabbar: Tabbar },
    meta: { title: '账单列表', auto: true }
  },
  {
    path: '/add',
    components: { default: Add, tabbar: Tabbar },
    meta: { title: '新增消费', auto: true }
  },
  {
    path: '/login',
    component: Login,
    meta: { title: '登录', auto: false }
  },
  {
    path: '/404',
    component: errorPage,
    meta: { title: '404', auto: false }
  },
  // 404 页面必须放在最后面
  { path: '*', redirect: '/404' }
]

// 替换路由的Push和replace方法
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, resolve, reject) {
  if (resolve || reject) return originalPush.call(this, location, resolve, reject)
  return originalPush.call(this, location).catch((e) => {})
}

const router = new VueRouter({
  routes,
  scrollBehavior: () => ({ y: 0 })
})

// 导航守卫
router.beforeEach((to, from, next) => {
  document.title = to.meta.title + '-囚墨记账系统'
  const token = store.state.user.token
  // 没登录却访问user下的路由
  if (!token && to.meta.auto) {
    return next('/login?returnUrl=' + encodeURIComponent(to.fullPath))
  }
  // 其他情况放行
  next()
})

export default router
